package it.progettoso.activity;

import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.view.KeyEvent;
import android.view.WindowManager;

public class LockScreenActivity extends Activity {

	private KeyguardManager.KeyguardLock mKeyguardLock = null;
	private static LockScreenActivity instance=null;
	private static boolean unlock=false;

	public LockScreenActivity() {
		instance=this;
	}

	public static LockScreenActivity getInstance(String command){
		if(instance==null){
			instance= new LockScreenActivity();
		}
		if(command.equals("unlock"))
			unlock=true;
		return instance;
	}
	


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		disableKeyguard();
		setContentView(R.layout.lock_main);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if(!unlock)
		   reLock();
	}
		
	@Override
	protected void onRestart() {
		super.onRestart();
		reLock();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		enableKeyguard();
	}

	protected void disableKeyguard() {
		if (mKeyguardLock == null) {
			KeyguardManager keyboardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
			mKeyguardLock = keyboardManager.newKeyguardLock("TAG");
		}
		mKeyguardLock.disableKeyguard();
	}

	protected void enableKeyguard() {
		if (mKeyguardLock != null) {
			mKeyguardLock.reenableKeyguard();
			mKeyguardLock = null;
		}
	}

	@Override
	public void onAttachedToWindow(){  
		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);     
		super.onAttachedToWindow(); 
	}


	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		default:
			return true;
		}
	}

	public void reLock(){
		LockScreenActivity.this.finish();
		PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
		PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
				| PowerManager.ACQUIRE_CAUSES_WAKEUP,
				"My Lock");
		wl.acquire();
		Intent lockintent = new Intent(this, LockScreenActivity.class);
		lockintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		this.startActivity(lockintent);
		wl.release();

	}


}